﻿using Microsoft.IdentityModel.Tokens;
using MyCompany.MyProject.Model.DTO;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MyCompany.MyProject.Extensions.Auth;

/// <summary>
/// JWT Token 生成类
/// </summary>
public class JwtToken
{
    /// <summary>
    /// 生成 Jwt Token
    /// </summary>
    /// <param name="claims">需要在登录的时候配置</param>
    /// <param name="permissionRequirement">在 startup 中定义的参数</param>
    /// <returns></returns>
    public static TokenInfoViewModel BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement)
    {
        var now = DateTime.Now;
        //var singingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sdfsdfsrty45634kkhllghtdgdfss345t678fs"));

        // 实例化 JwtSecurityToken
        var jwt = new JwtSecurityToken(
            issuer: permissionRequirement.Issuer,
            audience: permissionRequirement.Audience,
            claims: claims,
            notBefore: now,
            expires: now.Add(permissionRequirement.Expiration),
            signingCredentials: permissionRequirement.SigningCredentials
            );

        // 生成 Token
        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

        // 打包返回前台
        var responseJson = new TokenInfoViewModel()
        {
            success = true,
            token = encodedJwt,
            expires_in = permissionRequirement.Expiration.TotalSeconds,
            refreshTime = permissionRequirement.RefreshExpiration.TotalMinutes,
            token_type = "Bearer"
        };

        return responseJson;
    }
}
